/**
 * Created by Administrator on 2017/8/10.
 */
import {Link} from 'react-router-dom';
import {Select, Button, Input, Popconfirm, Form, Row, Col, Table, Breadcrumb, Icon,Modal} from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;

import * as Actions from './action'

import * as CONSTANTS from '../../common/utils/constants'
import {USER_STATUS, USER_TYPE} from '../../common/utils/constants'
import Utils from '../../common/utils/utils'

class App extends React.Component {
  state = {
    list: [
      {
        id: 1,
        loginPhone: 'admin',
        userName: '超级管理员',
        createTime: 24325342654
      }
    ],
    pagination: {current:0},
    loading: false,
    toAuditLoading: false,
    limit: 10,
    fileters: {}
  }

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.getList();
  }

  // 删除
  onDelete = (id, index) => {
    Actions.deleteAdmin(id).then(result => {
      if (result.errorCode == 0) {
        Utils.dialog.success('删除成功')
        let list = this.state.list
        list.splice(index, 1)
        this.setState({list})
      } else {
        Utils.dialog.error(result.msg)
      }
    })
  }

  handleUpdate = (id, index) => {

  }

  handleSearch = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      this.setState({
        fileters: values
      })
      //this.getList({...values})
    });
  }
  handleTableChange = (pagination, filters, sorter) => {
    const pager = {...this.state.pagination};
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    });
    this.getList({
      limit: this.state.limit ? this.state.limit : 10,
      page: pagination.current - 1,
      ...this.state.fileters
    });
  }
  getList = (params) => {
    params = {limit: 10, page: 0, ...this.state.fileters, ...params}
    this.setState({loading: true});
    //let {dispatch} = this.props
    Actions.getUserList(params).then((result) => {
      const pagination = {...this.state.pagination};
      pagination.current = result.body.page +1;
      pagination.total = result.body.totalCount;
      pagination.showTotal = (total) => {return `总共 ${total} 条`}
      console.log(result);
      let arr = result.body.rows;

      this.setState({
        loading: false,
        list: result.body.rows,
        pagination,
      });
    });

  }

  // 启用
  handleEnable = (id, index) => {
    let page = this;
     Actions.EnableUser({id}).then(response => {
       if (response.errorCode == 0) {
         Utils.dialog.success('启用成功')
         page.getList();
       } else {
         Utils.dialog.error(response.msg)
       }
     })
  }

  // 禁用
  handleDisable = (id, index) => {
    let page = this;
     Actions.DisableUser({id}).then(response => {
       if (response.errorCode == 0) {
         Utils.dialog.success('禁用成功')
         page.getList();
       } else {
         Utils.dialog.error(response.msg)
       }
     })
  }

  // 查看大图
  handleShowBigImg = (url) => {
    this.setState({
      imgBoxVisible: true,
      imgUrl: url
    });
    Modal.info({
      title: '查看大图',
      width: 500,
      content: (
          <div>
            <img src={url} alt="" width={300}/>
          </div>
      ),
      onOk() {},
    });
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {match} = this.props
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 19},
    };
    const colLayout = {
      xs: {span: 24},
      sm: {span: 8},
    };
    const columns = [
      {
        title: "头像",
        dataIndex: "headerImg",
        key: "headerImg",
        render: (url) => {
          return <img src={url} alt="" width={50}  style={{cursor: 'pointer'}} onClick={this.handleShowBigImg.bind(this, url)}/>
        }
      },
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName"
      },
    
      {
        title: "创建时间",
        dataIndex: "createdTime",
        key: "createdTime",
        render: (time) => {
          return Utils.formatDate(time, 'YYYY-MM-DD hh:ii')
        }
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status ",
        render: (text) => {
          return CONSTANTS.USER_STATUS[text]
        }
      },
      {
        title: "操作",
        dataIndex: "id",
        key: "id ",
        render: (id, record, index) => {
          let url = `${match.url}/detail/${id}`
          return (
            <div>
              {CONSTANTS.USER_STATUS[record.status] == '禁用' ?
                <Popconfirm placement="left" title={'确定启用该用户？'} onConfirm={() => this.handleEnable(id, index)}
                            okText="确定" cancelText="取消">
                  <Button icon='delete'>启用</Button>
                </Popconfirm> :
                <Popconfirm placement="left" title={'确定禁用该用户？'} onConfirm={() => this.handleDisable(id, index)}
                            okText="确定" cancelText="取消">
                  <Button icon='delete'>禁用</Button>
                </Popconfirm>
                 
              }
              <Link to={`${this.props.match.url}/question_list/${id}`}><Button>标记记录</Button></Link>
            </div>
          )
        }
      }
    ]
    return (
      <div id="wrap">
        <Breadcrumb className="breadcrumb">
          <Breadcrumb.Item>
            <Link to={`${match.url}`}>
              <Icon type="user"/>
              <span>用户管理列表</span>
            </Link>
          </Breadcrumb.Item>

        </Breadcrumb>
        <div className="content">
          <Form
            className="ant-advanced-search-form"
            onSubmit={this.handleSearch}
          >
            <Row
              gutter={40}>
              <Col {...colLayout} key='1'>
                <FormItem {...formItemLayout} label='用户名称'>
                  {getFieldDecorator('userName')(<Input />)}
                </FormItem>
              </Col>
              <Col {...colLayout} className='searchBtn'>
                <Button type="primary" htmlType="submit">查询</Button>
              </Col>
            </Row>
          </Form>

          <Table columns={columns}
                 rowKey='id'
                 dataSource={this.state.list}
                 pagination={this.state.pagination}
                 loading={this.state.loading}
                 onChange={this.handleTableChange}
          />
        </div>
      </div>
    )
  }
}

const List = Form.create()(App)
export default List


